<template>
    <div class="reader">
        <!-- 三个组件都是绝对定位，RaderCatalog要放到最下面，且不能被隐藏，因为currentChapter变化时要让目录列表滚动，如果ReaderCatalog组件
        display:none的话，没法控制列表滚动
    -->

        <ReaderCatalog
            :catalog="catalog"
            :currentChapter="currentChapter"
            :isScrollCatalog="isScrollCatalog"
            @change-chapter="changeChapter"
            @closeCatalog="closeCatalog"
        ></ReaderCatalog>

        <ReaderContent
            :content="content"
            :tit="tit"
            v-show="showContent"
            @controlMenu="controlMenu"
            @changeChapter="changeChapter"
        ></ReaderContent>

        <ReaderMenu
            :currentChapter="currentChapter"
            :catalogLength="catalog.length"
            :bookName="bookName"
            v-show="showMenu"
            @controlMenu="controlMenu"
            @changeChapter="changeChapter"
            @controlCatalog="controlCatalog"
        ></ReaderMenu>
    </div>
</template>

<script>
import ReaderContent from "@/components/ReaderContent.vue";
import ReaderCatalog from "@/components/ReaderCatalog.vue";
import ReaderMenu from "@/components/ReaderMenu.vue";
import { getCatalog, getContent, getBookInfo } from "@/api/index.js";
import { Modal } from "ant-design-vue";

export default {
    data: () => {
        return {
            bookName: null,
            catalog: [],
            content: null,
            tit: null,
            currentChapter: 0,
            showContent: true,
            showMenu: false,
            isScrollCatalog: false,
        };
    },
    beforeRouteLeave(to, from, next) {
        // this.addToBookcase();
        let bookUrl = this.$route.query.bookUrl;
        let bookCase = JSON.parse(localStorage.getItem("bookCase"));
        if (bookCase === null) {
            bookCase = [];
        }
        let isExistCase = false;
        for (let item of bookCase) {
            if (item.url === bookUrl) {
                isExistCase = true;
            }
        }
        if (!isExistCase) {
          let me = this
            Modal.confirm({
                title: "提示",
                content: "是否加入书架？",
                async onOk() {
                    me.addToBookcase();
                    next();
                },
                onCancel() {
                    next();
                },
            });
        } else {
            this.addToBookcase();
            next();
        }
        // this.$destroy();
        // next();
    },
    components: {
        ReaderCatalog,
        ReaderContent,
        ReaderMenu,
    },
    created() {
        this.startRead();
    },
    watch: {
        // 监听当前章节，获取文章内容
        currentChapter: function (val) {
            if (this.catalog.length === 0) return;
            this.fetchContent(this.catalog[val].chapterUrl);
        },
    },
    methods: {
        // 页面打开时，根据路由上的参数判断要显示哪一章
        async startRead() {
            const { bookUrl, currentChapter, bookName } = this.$route.query;
            this.bookName = bookName;
            this.currentChapter = parseInt(currentChapter)
            const res = await getCatalog({ url: bookUrl });
            this.catalog = res.data;
            let chapter = res.data[currentChapter];
            if (chapter) {
                this.fetchContent(chapter.chapterUrl);
            }
        },

        // 获取章节内容
        async fetchContent(chapterUrl) {
            console.log(chapterUrl);
            this.content = null;
            const res = await getContent({
                url: chapterUrl,
            });
            this.content = res.data.text
                .replace(/&#xA0;&#xA0;&#xA0;&#xA0;/gi, "&#xA0;&#xA0;")
                .replace(/<br><br>/gi, "<br>");
            this.tit = res.data.tit;
            this.showContent = true;
        },

        // 切换并显示章节
        changeChapter(param) {
            this.showContent = true;
            // 根据参数判断是切换到指定章节，还是切换前后章节
            var index = this.currentChapter;
            if (param === "pre") {
                //上一章
                index = index - 1;
                if (index < 0) {
                    alert("这就是第一章");
                    index = 0;
                } else {
                    this.content = null;
                }
            } else if (param === "next") {
                //下一章
                index = parseInt(index) + 1;
                if (index > this.catalog.length - 1) {
                    alert("最后一章了");
                    index = this.catalog.length - 1;
                } else {
                    this.content = null;
                }
            } else {
                //指定章节
                if (param !== this.currentChapter) {
                    this.content = null;
                }
                index = param;
            }
            this.currentChapter = parseInt(index);
            // console.log('index:'+index)
            // console.log('length:'+this.catalog.length)
        },
        // 显示/隐藏菜单
        controlMenu(param) {
            this.showContent = true;
            this.showMenu = param;
        },
        // 显示目录
        controlCatalog() {
            this.showContent = false;
            this.showMenu = false;
            this.isScrollCatalog = true;
        },

        // 退出
        async addToBookcase() {
            let bookUrl = this.$route.query.bookUrl;
            let currentChapter = this.currentChapter;
            let bookCase = JSON.parse(localStorage.getItem("bookCase"));
            if (bookCase === null) {
                bookCase = [];
            }
            let newBookCase = [];
            // 判断书架中有没有这本书
            let isExistCase = false;
            let book = null;
            for (let item of bookCase) {
                if (item.url === bookUrl) {
                    isExistCase = true;
                    book = item;
                } else {
                    newBookCase.push(item);
                }
            }
            //如果书架中有，就存起来，上面判断的时候就更新章节和顺序了
            if (isExistCase) {
                book.currentChapter=this.currentChapter;
                newBookCase.unshift(book);
                localStorage.setItem("bookCase", JSON.stringify(newBookCase));
            } else {
                let res = await getBookInfo({ url: bookUrl });
                book = res.data;
                book.currentChapter = currentChapter;
                newBookCase.unshift(book);
                localStorage.setItem("bookCase", JSON.stringify(newBookCase));
                //如果书架中没有，询问是否加入书架
                // Modal.confirm({
                //     title: "提示",
                //     content: "是否加入书架？",
                //     async onOk() {
                //         let res = await getBookInfo({ url: bookUrl });
                //         book = res.data;
                //         book.currentChapter = currentChapter;
                //         newBookCase.unshift(book);
                //         localStorage.setItem(
                //             "bookCase",
                //             JSON.stringify(newBookCase)
                //         );
                //     },
                //     onCancel() {},
                // });

                // let r = window.confirm("是否加入书架");
                // if (r === true) {
                //   let b = { bookUrl: bookUrl, currentChapter: currentChapter };
                //   let res = await getBookInfo({url:bookUrl})
                //   book = res.data;
                //   book.currentChapter = this.currentChapter
                //   // 放到最前面
                //   newBookCase.unshift(book);
                //   localStorage.setItem("bookCase", JSON.stringify(newBookCase));
                // }
            }
        },
        // 关闭目录
        closeCatalog() {
            this.showContent = true;
        },
    },
};
</script>

<style lang='less' scoped>
.reader {
    width: 100%;
    height: 100%;
    position: relative;
}
</style>